package com.yvan.example;

import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.p6spy.engine.spy.P6DataSource;
import com.yvan.data.mysql.autoconfig.CustomPaginationInterceptor;
import com.yvan.dynamic.datasource.DynamicRoutingDataSource;
import com.yvan.dynamic.datasource.autoconfigure.DynamicDataSourceProperties;
import com.yvan.dynamic.datasource.autoconfigure.druid.DruidDynamicDataSourceConfiguration;
import com.yvan.dynamic.datasource.provider.DynamicDataSourceProvider;
import org.springframework.boot.autoconfigure.AutoConfigureBefore;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;

import javax.sql.DataSource;

@Configuration
@EnableConfigurationProperties({DynamicDataSourceProperties.class})
@AutoConfigureBefore(
        name = {"org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration",
                "com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfigure"}
)
@Import({DruidDynamicDataSourceConfiguration.class})
public class P6SpyDataSourceAutoConfiguration {

    @Bean
    public DataSource dataSource(DynamicDataSourceProperties properties, DynamicDataSourceProvider dynamicDataSourceProvider) {

        DynamicRoutingDataSource dataSource = new DynamicRoutingDataSource();
        dataSource.setPrimary(properties.getPrimary());
        dataSource.setStrategy(properties.getStrategy());
        dataSource.setProvider(dynamicDataSourceProvider);
        dataSource.init();

        for (var entry : dataSource.getCurrentDataSources().entrySet()) {
            var p6ds = new P6DataSource(entry.getValue());
            entry.setValue(p6ds);
        }

        return dataSource;
    }

    @Bean
    @ConditionalOnMissingBean
    public CustomPaginationInterceptor paginationInterceptor() {
        CustomPaginationInterceptor paginationInterceptor = new CustomPaginationInterceptor();
        // 设置请求的页面大于最大页后操作， true调回到首页，false 继续请求  默认false
        paginationInterceptor.setOverflow(false);
        // 设置最大单页限制数量，默认 500 条，-1 不受限制
        paginationInterceptor.setLimit(500);
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        return paginationInterceptor;
    }


}
